﻿using System;
using System.Collections.Generic;
using System.Text;
using OnlineCourse.Model.Entity;
using OnlineCourse.Services.IServices;
using OnlineCourse.Services.Model;
using OnlineCourse.Model;
using System.Linq;
namespace OnlineCourse.Services
{
    public class PayOrderService : IPayOrderService
        
    {
        private readonly ApplicationDbContext _db;
        public PayOrderService( ApplicationDbContext db)
        {
            this._db = db;
        }
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="PaymentTypeId"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public bool AddPayOrder(out int mes, Guid PaymentTypeId, Guid UserId)
        {
            
            bool mark = false;
            //在PayOrder表里增加一条记录
            //先通过ID获取相关的对象
            PayOrder po = new PayOrder();
            PaymentType pt = new PaymentType();
            User u = new User();
            pt = _db.PaymentTypes.Where(a => a.Id == PaymentTypeId).FirstOrDefault();
            u = _db.Users.Where(a => a.Id == UserId).FirstOrDefault();
            po.PaymentType = pt;
            po.PaymentTypeId = pt.Id;
            po.UserId = u.Id;
            po.User = u;
            u.Account = u.Account + pt.AccountMoney;
            if (string.IsNullOrEmpty(PaymentTypeId.ToString()) || string.IsNullOrEmpty(UserId.ToString()))
            {
                mes = 4;//参数为空
                return false;

            }
            try
            {
                _db.PayOrders.Add(po);
               
                if(_db.SaveChanges()>1)
                {
                    mes = 0;//成功
                    mark = true;
                }
                else
                {
                    mes = 3;//数据库操作失败
                }

            }
            catch (Exception ee)
            {

                throw ee;
            }
            return mark;
           
        }
        /// <summary>
        ///  分页查询所有的充值列表
        /// </summary>
        /// <param name="total"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<PayOrderQueryModel> getPayOrderlist(out int total, int page = 1, int pageSize = 10)
        {
            List<PayOrderQueryModel> poqm = new List<PayOrderQueryModel>();
            poqm = _db.PayOrders.Select(a => new PayOrderQueryModel() { Title = a.PaymentType.Title, UserName = a.User.UserName, PaymentTypeId = a.PaymentTypeId, Createtime = a.CreatedDate, Price = a.PaymentType.Price, AccountMoney = a.PaymentType.AccountMoney }).ToList();
            total = poqm.Count();
            return poqm;
        }
    }
}
